public class Board {
    private final int width;
    private final int height;
    private int[][] grid;
    private int score = 0;

    public Board(int width, int height) {
        this.width = width;
        this.height = height;
        grid = new int[height][width];
    }

    public boolean checkCollision(int[][] shape, int x, int y) {
        for (int row = 0; row < shape.length; row++) {
            for (int col = 0; col < shape[row].length; col++) {
                if (shape[row][col] != 0) {
                    int boardX = x + col;
                    int boardY = y + row;

                    // 检查边界
                    if (boardX < 0 || boardX >= width || boardY < 0 || boardY >= height) {
                        return true;
                    }

                    // 检查已放置的方块
                    if (grid[boardY][boardX] != 0) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public void setCell(int x, int y, int value) {
        if (x >= 0 && x < width && y >= 0 && y < height) {
            grid[y][x] = value;
        }
    }

    public int getHeight() {
        return this.height;
    }

    public int getWidth() {
        return this.width;
    }

    public int getCell(int x, int y) {
        return grid[y][x];
    }

    public boolean isGameOver() {
        for (int col = 0; col < width; col++) {
            if (grid[0][col] != 0) {
                return true;
            }
        }
        return false;
    }

    public void clearFullRows() {
        for (int row = height - 1; row >= 0; row--) {
            if (isFullRow(row)) {
                moveRowsDown(row);
                row++; // Re-check the same row after moving rows down
                score +=10;
            }
        }
    }

    private boolean isFullRow(int row) {
        for (int col = 0; col < width; col++) {
            if (grid[row][col] == 0) {
                return false;
            }
        }
        return true;
    }

    private void moveRowsDown(int startRow) {
        for (int row = startRow; row > 0; row--) {
            for (int col = 0; col < width; col++) {
                grid[row][col] = grid[row - 1][col];
            }
        }

        // Clear the top row
        for (int col = 0; col < width; col++) {
            grid[0][col] = 0;
        }
    }

    public int getScore() {
        return this.score;
    }
}
